package com.css.fxfzypg.modules.SettingSeismic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.manage.lethalitydifference.repository.entity.LethalityDifferenceEntity;
import com.css.fxfzypg.manage.lethalitydifference.service.LethalityDifferenceService;
import com.css.fxfzypg.modules.SettingSeismic.entity.SeismicIntensityRelation;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicDetails;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicProcess;
import com.css.fxfzypg.modules.SettingSeismic.queryParams.SeismicRelationQueryParams;
import com.css.fxfzypg.modules.SettingSeismic.repository.IntensityRelationRepository;
import com.css.fxfzypg.modules.SettingSeismic.service.IntensityRelationService;
import com.css.fxfzypg.modules.SettingSeismic.service.SettingSeismicService;
import com.css.fxfzypg.modules.baseData.entity.PbeEntity;
import com.css.fxfzypg.modules.baseData.service.BasicDataService;
import com.css.fxfzypg.modules.baseData.service.PbeService;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.PlantPbe;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.SeismicInfluenceflyPbe;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.SettingSeismicInfluenceflied;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.YpgResultSlope;
import com.css.fxfzypg.modules.earthquakedisasterloss.repository.CountLandslideRepository;
import com.css.fxfzypg.modules.earthquakedisasterloss.repository.SettingSeismicInfluencefliedRepository;
import com.css.fxfzypg.modules.earthquakedisasterloss.service.YpgResultPbeService;
import com.css.fxfzypg.modules.maps.service.InfluencefliedMapService;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.model.entity.*;
import com.css.fxfzypg.modules.model.service.*;
import com.css.fxfzypg.modules.preAssessResult.entity.SeiCapDistribution;
import com.css.fxfzypg.modules.preAssessResult.service.PreAssessResultService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultEntity;
import com.css.fxfzypg.modules.resultupload.service.ResultService;
import com.css.fxfzypg.modules.resultupload.service.ResultTotalService;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: fxfzypg
 * @Author: lhl
 * @CreateDate: 2022/10/20 14:25
 */
@Service
public class IntensityRelationServiceImpl implements IntensityRelationService {

    @Resource
    IntensityRelationRepository intensityRelationRepository;
    @Resource
    IntensityAttenuationService intensityAttenuationService;
    @Resource
    CasualtyService casualtyService;
    @Resource
    EconomicLossesService economicLossesService;
    @Resource
    ResettlementPersonnelService resettlementPersonnelService;
    @Resource
    MaterialService materialService;
    @Resource
    RescueForceService rescueForceService;

    @Resource
    SettingSeismicService settingSeismicService;
    @Resource
    SUserService sUserService;
    @Resource
    SettingSeismicInfluencefliedRepository settingSeismicInfluencefliedRepository;
    @Resource
    PreAssessTaskService preAssessTaskService;
    @Resource
    SysAreaService sysAreaService;
    @Resource
    SetEarthquakeMapService setEarthquakeMapService;
    @Resource
    InfluencefliedMapService influencefliedMapService;//地图使用--导入影响场
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    BasicDataService basicDataService;
    @Resource
    ResultTotalService resultTotalService;
    @Resource
    YpgResultPbeService ypgResultPbeService;

    @Resource
    PreAssessResultService preAssessResultService;
    @Resource
    CountLandslideRepository countLandslideRepository;
    @Resource
    LethalityDifferenceService lethalityDifferenceService;


    @Override
    public RestResponse getAll(String taskId) throws UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
        String modelType = "1";
        SeismicIntensityRelation byTaskId = intensityRelationRepository.getByTaskId(taskId);
        if (PlatformObjectUtils.isNotEmpty(byTaskId)) {
            if (PlatformObjectUtils.isNotEmpty(byTaskId.getModel1Type())) {
                modelType = byTaskId.getModel1Type();
            }
        }
        jsonObject = getDefault1ByTaskId(taskId, modelType, 1);
        // List<SettingSeismicInfluenceflied> settingSeismicInfluenceflieds = settingSeismicInfluencefliedRepository.findByTaskId(taskId);
        // if (settingSeismicInfluenceflieds.size() > 0) {
        //     if (PlatformObjectUtils.isEmpty(modelType)) {
        //         jsonObject.put("type1", "1");
        //     } else {
        //         if ("1".equals(modelType)) {
        //             jsonObject.put("type1", "1");
        //         } else if ("2".equals(modelType)) {
        //             jsonObject.put("type1", "2");
        //         } else if ("3".equals(modelType)) {//导入影响场
        //             jsonObject.put("type1", "3");
        //         }
        //     }
        // } else {
        //     jsonObject.put("type1", "0");
        // }
        jsonObject.put("entity2", getDefault2ByTaskId(taskId).get("entity2"));
        // int rysw = basicDataService.getPbeInjuriesByTaskId(taskId);
        // if (rysw > 0) {
        //     jsonObject.put("type2", "1");
        // } else {
        //     jsonObject.put("type2", "0");
        // }
        jsonObject.put("entity3", getDefault3ByTaskId(taskId).get("entity3"));
        // int economic = basicDataService.getPbeLossesByTaskId(taskId);
        // if (economic > 0) {
        //     jsonObject.put("type3", "1");
        // } else {
        //     jsonObject.put("type3", "0");
        // }
        jsonObject.put("entity4", getDefault4ByTaskId(taskId).get("entity4"));
        // if (PlatformObjectUtils.isNotEmpty(byTaskId)) {
        //     if (PlatformObjectUtils.isNotEmpty(byTaskId.getModel4Type())) {
        //         modelType = byTaskId.getModel4Type();
        //     }
        // }
        // List<PlantPbe> byTaskId1 = ypgResultPbeService.getByTaskId(taskId);
        // if (byTaskId1.size() > 0) {
        //     if (PlatformObjectUtils.isEmpty(modelType)) {
        //         jsonObject.put("type4", "1");
        //     } else {
        //         if ("1".equals(modelType)) {
        //             jsonObject.put("type4", "1");
        //         } else if ("2".equals(modelType)) {
        //             jsonObject.put("type4", "2");
        //         }
        //     }
        // } else {
        //     jsonObject.put("type4", "0");
        // }
        jsonObject.put("entity5", getDefault5ByTaskId(taskId).get("entity5"));
        // if (PlatformObjectUtils.isNotEmpty(byTaskId)) {
        //     if ("1".equals(byTaskId.getExtends1())) {
        //         jsonObject.put("type5", "1");
        //     } else {
        //         jsonObject.put("type5", "0");
        //     }
        // } else {
        //     jsonObject.put("type5", "0");
        // }
        jsonObject.put("entity6", getDefault6ByTaskId(taskId).get("entity6"));
        // if (PlatformObjectUtils.isNotEmpty(byTaskId)) {
        //     if ("1".equals(byTaskId.getExtends2())) {
        //         jsonObject.put("type6", "1");
        //     } else {
        //         jsonObject.put("type6", "0");
        //     }
        // } else {
        //     jsonObject.put("type6", "0");
        // }
        List<YpgResultSlope> byTaskId2 = countLandslideRepository.getByTaskId(taskId);
        if (byTaskId2.size()>0) {
            YpgResultSlope ypgResultSlope = byTaskId2.get(0);
            if (PlatformObjectUtils.isNotEmpty(ypgResultSlope)) {
                String dzIntensity = ypgResultSlope.getDzIntensity();
                switch (dzIntensity) {
                    case "6":
                        dzIntensity = "Ⅵ";
                        break;
                    case "7":
                        dzIntensity = "Ⅶ";
                        break;
                    case "8":
                        dzIntensity = "Ⅷ";
                        break;
                    case "9":
                        dzIntensity = "Ⅸ";
                        break;
                    case "10":
                        dzIntensity = "Ⅹ";
                        break;
                    case "11":
                        dzIntensity = "Ⅺ";
                        break;
                }
                ypgResultSlope.setDzIntensity(dzIntensity);
                jsonObject.put("entity7", ypgResultSlope);
            }
        }

        jsonObject.put("seismicIntensityRelation",byTaskId);
        // if (PlatformObjectUtils.isNotEmpty(byTaskId)) {
        //     modelType = byTaskId.getModel7Type();
        //     if (PlatformObjectUtils.isNotEmpty(modelType)) {
        //         jsonObject.put("type7", modelType);
        //     } else {
        //         jsonObject.put("type7", "0");
        //     }
        // } else {
        //     jsonObject.put("type7", "0");
        // }

        //抗震能力分布
        // List<SeiCapDistribution> seiCapCalculation = preAssessResultService.getSeiCapCalculation(taskId, "");
        // if (seiCapCalculation.size() > 0) {
        //     jsonObject.put("type8", "1");
        // } else {
        //     jsonObject.put("type8", "0");
        // }

        //区县致死性差异性分析
        // String flag = lethalityDifferenceService.getCreateFlag(taskId);
        // jsonObject.put("type9", flag);
        return ResponseCreator.createSuccessResponse(jsonObject, "查询成功！");
    }

    @Override
    public RestResponse getDefault1ByTaskId(String taskId) {
        return ResponseCreator.createSuccessResponse(getDefault1ByTaskId(taskId, "1", 0), "查询成功！");
    }

    private JSONObject getDefault1ByTaskId(String taskId, String model1Type, int isNa) {
        JSONObject jsonObject = new JSONObject();
        List<Object> list = new ArrayList<>();
        IntensityAttenuation intensityAttenuation = null;
        if (isNa == 1) {
            intensityAttenuation = (IntensityAttenuation) intensityRelationRepository.getModelByTaskId(taskId, "1");
        }
        if (PlatformObjectUtils.isEmpty(intensityAttenuation)) {
            List<IntensityAttenuation> defaultModel = getDefaultModel(taskId, 0, "1");
            if (defaultModel == null) {
                intensityAttenuation = intensityAttenuationService.getDefaultModel();
            } else {
                intensityAttenuation = defaultModel.get(0);
            }
        }
        Map<String, String> map = convertEntity(intensityAttenuation.getProvince(), intensityAttenuation.getCity());
        intensityAttenuation.setProvince(map.get("province"));
        intensityAttenuation.setCity(map.get("city"));
        list.add(intensityAttenuation);

        if ("2".equals(model1Type)) {
            SettingSeismicProcess processByTaskId = intensityRelationRepository.getProcessByTaskId(taskId);
            if (PlatformObjectUtils.isNotEmpty(processByTaskId)) {
                list.add(processByTaskId);
            }
        }
        jsonObject.put("entity1", list);
        return jsonObject;
    }

    private JSONObject getDefault2ByTaskId(String taskId) {
        JSONObject jsonObject = new JSONObject();
        Casualty entity = (Casualty) intensityRelationRepository.getModelByTaskId(taskId, "2");
        if (PlatformObjectUtils.isEmpty(entity)) {
            List<Casualty> defaultModel = getDefaultModel(taskId, 0, "2");
            if (defaultModel == null) {
                entity = casualtyService.getDefaultModel();
            } else {
                entity = defaultModel.get(0);
            }
        }
        Map<String, String> map = convertEntity(entity.getProvince(), entity.getCity());
        entity.setProvince(map.get("province"));
        entity.setCity(map.get("city"));
        jsonObject.put("entity2", entity);
        return jsonObject;
    }

    private JSONObject getDefault3ByTaskId(String taskId) {
        JSONObject jsonObject = new JSONObject();
        EconomicLosses entity = (EconomicLosses) intensityRelationRepository.getModelByTaskId(taskId, "3");
        if (PlatformObjectUtils.isEmpty(entity)) {
            List<EconomicLosses> defaultModel = getDefaultModel(taskId, 0, "3");
            if (defaultModel == null) {
                entity = economicLossesService.getDefaultModel();
            } else {
                entity = defaultModel.get(0);
            }
        }
        Map<String, String> map = convertEntity(entity.getProvince(), entity.getCity());
        entity.setProvince(map.get("province"));
        entity.setCity(map.get("city"));
        jsonObject.put("entity3", entity);
        return jsonObject;
    }

    private JSONObject getDefault4ByTaskId(String taskId) {
        JSONObject jsonObject = new JSONObject();
        ResettlementPersonnel entity = (ResettlementPersonnel) intensityRelationRepository.getModelByTaskId(taskId, "4");
        if (PlatformObjectUtils.isEmpty(entity)) {
            List<ResettlementPersonnel> defaultModel = getDefaultModel(taskId, 0, "4");
            if (defaultModel == null) {
                entity = resettlementPersonnelService.getDefaultModel();
            } else {
                entity = defaultModel.get(0);
            }
        }
        Map<String, String> map = convertEntity(entity.getProvince(), entity.getCity());
        entity.setProvince(map.get("province"));
        entity.setCity(map.get("city"));
        jsonObject.put("entity4", entity);
        return jsonObject;
    }

    private JSONObject getDefault5ByTaskId(String taskId) {
        JSONObject jsonObject = new JSONObject();
        RescueForceEntity entity = (RescueForceEntity) intensityRelationRepository.getModelByTaskId(taskId, "5");
        if (PlatformObjectUtils.isEmpty(entity)) {
            List<RescueForceEntity> defaultModel = getDefaultModel(taskId, 0, "5");
            if (defaultModel == null) {
                entity = rescueForceService.getDefaultModel();
            } else {
                entity = defaultModel.get(0);
            }
        }
        Map<String, String> map = convertEntity(entity.getProvince(), entity.getCity());
        entity.setProvince(map.get("province"));
        entity.setCity(map.get("city"));
        jsonObject.put("entity5", entity);
        return jsonObject;
    }

    private JSONObject getDefault6ByTaskId(String taskId) {
        JSONObject jsonObject = new JSONObject();
        Material entity = (Material) intensityRelationRepository.getModelByTaskId(taskId, "6");
        if (PlatformObjectUtils.isEmpty(entity)) {
            List<Material> defaultModel = getDefaultModel(taskId, 0, "6");
            if (defaultModel == null) {
                entity = materialService.getDefaultModel();
            } else {
                entity = defaultModel.get(0);
            }
        }
        Map<String, String> map = convertEntity(entity.getProvince(), entity.getCity());
        entity.setProvince(map.get("province"));
        entity.setCity(map.get("city"));
        jsonObject.put("entity6", entity);
        return jsonObject;
    }

    @Override
    public RestResponse getModelByTaskId(SeismicRelationQueryParams queryParams, int curPage, int pageSize) {
        JSONObject jsonObject = new JSONObject();
        List defaultModel = getDefaultModel(queryParams.getTaskId(), 1, queryParams.getType());
        if (defaultModel.size() > 0) {
            int page = (curPage - 1) * pageSize;
            String province = queryParams.getProvince();
            if (PlatformObjectUtils.isEmpty(province)) {
                if (page < defaultModel.size()) {
                    if (page + pageSize > defaultModel.size()) {
                        switch (queryParams.getType()) {
                            case "1":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, defaultModel.size()), "1"));
                                break;
                            case "2":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, defaultModel.size()), "2"));
                                break;
                            case "3":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, defaultModel.size()), "3"));
                                break;
                            case "4":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, defaultModel.size()), "4"));
                                break;
                            case "5":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, defaultModel.size()), "5"));
                                break;
                            case "6":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, defaultModel.size()), "6"));
                                break;

                        }
                    } else {
                        switch (queryParams.getType()) {
                            case "1":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, page + pageSize), "1"));
                                break;
                            case "2":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, page + pageSize), "2"));
                                break;
                            case "3":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, page + pageSize), "3"));
                                break;
                            case "4":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, page + pageSize), "4"));
                                break;
                            case "5":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, page + pageSize), "5"));
                                break;
                            case "6":
                                jsonObject.put("rows", convertList(defaultModel.subList(page, page + pageSize), "6"));
                                break;

                        }
                    }
                    jsonObject.put("total", defaultModel.size());
                    return ResponseCreator.createSuccessResponse(jsonObject, "查询成功！");
                }
            } else {
                switch (queryParams.getType()) {
                    case "1":
                        jsonObject.put("rows", convertList(getSublist1(queryParams, defaultModel, page, pageSize), "1"));
                        break;
                    case "2":
                        jsonObject.put("rows", convertList(getSublist2(queryParams, defaultModel, page, pageSize), "2"));
                        break;
                    case "3":
                        jsonObject.put("rows", convertList(getSublist3(queryParams, defaultModel, page, pageSize), "3"));
                        break;
                    case "4":
                        jsonObject.put("rows", convertList(getSublist4(queryParams, defaultModel, page, pageSize), "4"));
                        break;
                    case "5":
                        jsonObject.put("rows", convertList(getSublist5(queryParams, defaultModel, page, pageSize), "5"));
                        break;
                    case "6":
                        jsonObject.put("rows", convertList(getSublist6(queryParams, defaultModel, page, pageSize), "6"));
                        break;
                }
                jsonObject.put("total", defaultModel.size());
                return ResponseCreator.createSuccessResponse(jsonObject, "查询成功！");
            }
        }
        jsonObject.put("rows", new ArrayList<>());
        jsonObject.put("total", 0);
        return ResponseCreator.createSuccessResponse(jsonObject, "查询成功！");
    }

    private Map<String, List<String>> getTaskDistrict(String taskId) {
        PreAssessTaskEntity preAssessTaskEntity = preAssessTaskService.getById(taskId);
        String taskDistrict = preAssessTaskEntity.getTaskDistrict();
        Map<String, List<String>> listMap = new HashMap<>();
        String[] split = taskDistrict.split("、");
        if (split.length > 1) {
            for (String a : split) {
                String[] split1 = a.split("-");
                List<String> list = null;
                if (listMap.containsKey(split1[0])) {
                    list = listMap.get(split1[0]);
                    if (split1.length > 1) {
                        if (list.contains(split1[1])) {
                            list.add(split1[1]);
                        }
                    }
                } else {
                    list = new ArrayList<>();
                    if (split1.length > 1) {
                        list.add(split1[1]);
                    }
                    listMap.put(split1[0], list);
                }
            }
        } else {
            String[] split1 = split[0].split("-");
            List<String> list = new ArrayList<>();
            if (split1.length > 1) {
                list.add(split1[1]);
            }
            listMap.put(split1[0], list);
        }
        return listMap;
    }

    private List getDefaultModel(String taskId, int isNa, String type) {
        Map<String, List<String>> listMap = getTaskDistrict(taskId);
        List iaList = new ArrayList<>();
        for (String key : listMap.keySet()) {
            List<String> list = listMap.get(key);
            for (String s : list) {
                String divisionIds = null;
                try {
                    //判断省市县的名称是否符合规范
                    if ("北京市".equals(key) || "天津市".equals(key) || "重庆市".equals(key) || "上海市".equals(key)) {
                        if (s.equals(key)) {
                            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(key, "utf-8"),
                                    "", "");
                        } else {
                            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(key, "utf-8"),
                                    URLEncoder.encode(key, "utf-8"), URLEncoder.encode(s, "utf-8"));
                        }
                    } else {
                        divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(key, "utf-8"),
                                URLEncoder.encode(s, "utf-8"), "");
                    }
                } catch (Exception e) {
                    return null;
                }
                String[] split1 = divisionIds.split("_");
                if (split1.length < 2) {
                    System.out.println(key + "-" + s + "===============" + split1.toString());
                    return null;
                }
                List byDivision1 = null;
                switch (type) {
                    case "1":
                        byDivision1 = intensityAttenuationService.getByDivision(split1[0], split1[1], isNa);
                        break;
                    case "2":
                        byDivision1 = casualtyService.getByDivision(split1[0], split1[1], isNa);
                        break;
                    case "3":
                        byDivision1 = economicLossesService.getByDivision(split1[0], split1[1], isNa);
                        break;
                    case "4":
                        byDivision1 = resettlementPersonnelService.getByDivision(split1[0], split1[1], isNa);
                        break;
                    case "5":
                        byDivision1 = rescueForceService.getByDivision(split1[0], split1[1], isNa);
                        break;
                    case "6":
                        byDivision1 = materialService.getByDivision(split1[0], split1[1], isNa);
                        break;
                }
                if (PlatformObjectUtils.isEmpty(byDivision1)) {
                    continue;
                }
                if (byDivision1.size() == 0) {
                    continue;
                }
                if (isNa == 1) {
                    iaList.addAll(byDivision1);
                } else {
                    iaList.add(byDivision1.get(0));
                }
            }
            if (list.size() < 1) {
                String divisionIds = null;
                try {
                    //判断省市县的名称是否符合规范
                    divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(key, "utf-8"),
                            "", "");
                } catch (Exception e) {
                    return null;
                }
                List byDivision1 = null;
                switch (type) {
                    case "1":
                        byDivision1 = intensityAttenuationService.getByDivision(divisionIds, null, isNa);
                        break;
                    case "2":
                        byDivision1 = casualtyService.getByDivision(divisionIds, null, isNa);
                        break;
                    case "3":
                        byDivision1 = economicLossesService.getByDivision(divisionIds, null, isNa);
                        break;
                    case "4":
                        byDivision1 = resettlementPersonnelService.getByDivision(divisionIds, null, isNa);
                        break;
                    case "5":
                        byDivision1 = rescueForceService.getByDivision(divisionIds, null, isNa);
                        break;
                    case "6":
                        byDivision1 = materialService.getByDivision(divisionIds, null, isNa);
                        break;

                }
                if (PlatformObjectUtils.isEmpty(byDivision1)) {
                    continue;
                }
                if (byDivision1.size() == 0) {
                    continue;
                }
                if (isNa == 1) {
                    iaList.addAll(byDivision1);
                } else {
                    iaList.add(byDivision1.get(0));
                }
            } else {
                String divisionIds = null;
                try {
                    //判断省市县的名称是否符合规范
                    divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(key, "utf-8"),
                            "", "");
                } catch (Exception e) {
                    return null;
                }
                List byDivision1 = null;
                switch (type) {
                    case "1":
                        byDivision1 = intensityAttenuationService.getByDivision(divisionIds, "全部", isNa);
                        break;
                    case "2":
                        byDivision1 = casualtyService.getByDivision(divisionIds, "全部", isNa);
                        break;
                    case "3":
                        byDivision1 = economicLossesService.getByDivision(divisionIds, "全部", isNa);
                        break;
                    case "4":
                        byDivision1 = resettlementPersonnelService.getByDivision(divisionIds, "全部", isNa);
                        break;
                    case "5":
                        byDivision1 = rescueForceService.getByDivision(divisionIds, "全部", isNa);
                        break;
                    case "6":
                        byDivision1 = materialService.getByDivision(divisionIds, "全部", isNa);
                        break;
                }
                if (PlatformObjectUtils.isEmpty(byDivision1)) {
                    continue;
                }
                if (byDivision1.size() == 0) {
                    continue;
                }
                if (isNa == 1) {
                    iaList.addAll(byDivision1);
                } else {
                    iaList.add(byDivision1.get(0));
                }
            }
        }
        if (isNa == 1) {
            return iaList;
        }
        if (iaList.size() < 1) {
            return null;
        }
        switch (type) {
            case "1":
                List<Date> dateList1 = ((List<IntensityAttenuation>) iaList).stream().map(IntensityAttenuation::getCreateTime).collect(Collectors.toList());
                Date date1 = dateList1.stream().max(Date::compareTo).get();
                IntensityAttenuation entity1 = ((List<IntensityAttenuation>) iaList).stream().filter(s -> !(s.getCreateTime().before(date1))).findFirst().get();
                return Collections.singletonList(entity1);
            case "2":
                List<Date> dateList2 = ((List<Casualty>) iaList).stream().map(Casualty::getCreateTime).collect(Collectors.toList());
                Date date2 = dateList2.stream().max(Date::compareTo).get();
                Casualty entity2 = ((List<Casualty>) iaList).stream().filter(s -> !(s.getCreateTime().before(date2))).findFirst().get();
                return Collections.singletonList(entity2);
            case "3":
                List<Date> dateList3 = ((List<EconomicLosses>) iaList).stream().map(EconomicLosses::getCreateTime).collect(Collectors.toList());
                Date date3 = dateList3.stream().max(Date::compareTo).get();
                EconomicLosses entity3 = ((List<EconomicLosses>) iaList).stream().filter(s -> !(s.getCreateTime().before(date3))).findFirst().get();
                return Collections.singletonList(entity3);
            case "4":
                List<Date> dateList4 = ((List<ResettlementPersonnel>) iaList).stream().map(ResettlementPersonnel::getCreateTime).collect(Collectors.toList());
                Date date4 = dateList4.stream().max(Date::compareTo).get();
                ResettlementPersonnel entity4 = ((List<ResettlementPersonnel>) iaList).stream().filter(s -> !(s.getCreateTime().before(date4))).findFirst().get();
                return Collections.singletonList(entity4);
            case "5":
                List<Date> dateList6 = ((List<RescueForceEntity>) iaList).stream().map(RescueForceEntity::getCreateTime).collect(Collectors.toList());
                Date date6 = dateList6.stream().max(Date::compareTo).get();
                RescueForceEntity entity6 = ((List<RescueForceEntity>) iaList).stream().filter(s -> !(s.getCreateTime().before(date6))).findFirst().get();
                return Collections.singletonList(entity6);
            case "6":
                List<Date> dateList5 = ((List<Material>) iaList).stream().map(Material::getCreateTime).collect(Collectors.toList());
                Date date5 = dateList5.stream().max(Date::compareTo).get();
                Material entity5 = ((List<Material>) iaList).stream().filter(s -> !(s.getCreateTime().before(date5))).findFirst().get();
                return Collections.singletonList(entity5);
        }
        return new ArrayList();
    }

    private List convertList(List list, String type) {
        for (int i = 0; i < list.size(); i++) {
            switch (type) {
                case "1":
                    IntensityAttenuation entity1 = (IntensityAttenuation) list.get(i);
                    Map<String, String> map1 = convertEntity(entity1.getProvince(), entity1.getCity());
                    entity1.setProvince(map1.get("province"));
                    entity1.setCity(map1.get("city"));
                    list.set(i, entity1);
                    break;
                case "2":
                    Casualty entity2 = (Casualty) list.get(i);
                    Map<String, String> map2 = convertEntity(entity2.getProvince(), entity2.getCity());
                    entity2.setProvince(map2.get("province"));
                    entity2.setCity(map2.get("city"));
                    list.set(i, entity2);
                    break;
                case "3":
                    EconomicLosses entity3 = (EconomicLosses) list.get(i);
                    Map<String, String> map3 = convertEntity(entity3.getProvince(), entity3.getCity());
                    entity3.setProvince(map3.get("province"));
                    entity3.setCity(map3.get("city"));
                    list.set(i, entity3);
                    break;
                case "4":
                    ResettlementPersonnel entity4 = (ResettlementPersonnel) list.get(i);
                    Map<String, String> map4 = convertEntity(entity4.getProvince(), entity4.getCity());
                    entity4.setProvince(map4.get("province"));
                    entity4.setCity(map4.get("city"));
                    list.set(i, entity4);
                    break;
                case "5":
                    RescueForceEntity entity6 = (RescueForceEntity) list.get(i);
                    Map<String, String> map6 = convertEntity(entity6.getProvince(), entity6.getCity());
                    entity6.setProvince(map6.get("province"));
                    entity6.setCity(map6.get("city"));
                    list.set(i, entity6);
                    break;
                case "6":
                    Material entity5 = (Material) list.get(i);
                    Map<String, String> map5 = convertEntity(entity5.getProvince(), entity5.getCity());
                    entity5.setProvince(map5.get("province"));
                    entity5.setCity(map5.get("city"));
                    list.set(i, entity5);
                    break;
            }
        }
        return list;
    }

    private Map<String, String> convertEntity(String province, String city) {
        Map<String, String> areaMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap"));
        Map<String, String> map = new HashMap<>();
        map.put("province", areaMap.get(province));
        if (!"全部".equals(city)) {
            StringBuilder buffer = new StringBuilder();
            String[] cityList = city.split(",");
            for (String s : cityList) {
                buffer.append(areaMap.get(s)).append(",");
            }
            String cityName = buffer.toString();
            map.put("city", cityName.substring(0, cityName.length() - 1));
        } else {
            map.put("city", city);
        }
        return map;
    }

    private List<IntensityAttenuation> getSublist1(SeismicRelationQueryParams queryParams, List defaultModel,
                                                   int page, int pageSize) {
        String province = queryParams.getProvince();
        List<IntensityAttenuation> list = new ArrayList<>();
        if (page < defaultModel.size()) {
            String city = queryParams.getCity();
            int count = 0;
            for (int i = 0; i < defaultModel.size(); i++) {
                IntensityAttenuation entity = (IntensityAttenuation) defaultModel.get(i);
                if (PlatformObjectUtils.isEmpty(city)) {
                    if (province.equals(entity.getProvince())) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                } else {
                    if (province.equals(entity.getProvince()) && entity.getCity().contains(city)) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                }
            }
        }
        return list;
    }

    private List<Casualty> getSublist2(SeismicRelationQueryParams queryParams, List defaultModel,
                                       int page, int pageSize) {
        String province = queryParams.getProvince();
        List<Casualty> list = new ArrayList<>();
        if (page < defaultModel.size()) {
            String city = queryParams.getCity();
            int count = 0;
            for (int i = 0; i < defaultModel.size(); i++) {
                Casualty entity = (Casualty) defaultModel.get(i);
                if (PlatformObjectUtils.isEmpty(city)) {
                    if (province.equals(entity.getProvince())) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                } else {
                    if (province.equals(entity.getProvince()) && entity.getCity().contains(city)) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                }
            }
        }
        return list;
    }

    private List<EconomicLosses> getSublist3(SeismicRelationQueryParams queryParams, List defaultModel,
                                             int page, int pageSize) {
        String province = queryParams.getProvince();
        List<EconomicLosses> list = new ArrayList<>();
        if (page < defaultModel.size()) {
            String city = queryParams.getCity();
            int count = 0;
            for (int i = 0; i < defaultModel.size(); i++) {
                EconomicLosses entity = (EconomicLosses) defaultModel.get(i);
                if (PlatformObjectUtils.isEmpty(city)) {
                    if (province.equals(entity.getProvince())) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                } else {
                    if (province.equals(entity.getProvince()) && entity.getCity().contains(city)) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                }
            }
        }
        return list;
    }

    private List<ResettlementPersonnel> getSublist4(SeismicRelationQueryParams queryParams, List defaultModel,
                                                    int page, int pageSize) {
        String province = queryParams.getProvince();
        List<ResettlementPersonnel> list = new ArrayList<>();
        if (page < defaultModel.size()) {
            String city = queryParams.getCity();
            int count = 0;
            for (int i = 0; i < defaultModel.size(); i++) {
                ResettlementPersonnel entity = (ResettlementPersonnel) defaultModel.get(i);
                if (PlatformObjectUtils.isEmpty(city)) {
                    if (province.equals(entity.getProvince())) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                } else {
                    if (province.equals(entity.getProvince()) && entity.getCity().contains(city)) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                }
            }
        }
        return list;
    }

    private List<Material> getSublist5(SeismicRelationQueryParams queryParams, List defaultModel,
                                       int page, int pageSize) {
        String province = queryParams.getProvince();
        List<Material> list = new ArrayList<>();
        if (page < defaultModel.size()) {
            String city = queryParams.getCity();
            int count = 0;
            for (int i = 0; i < defaultModel.size(); i++) {
                Material entity = (Material) defaultModel.get(i);
                if (PlatformObjectUtils.isEmpty(city)) {
                    if (province.equals(entity.getProvince())) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                } else {
                    if (province.equals(entity.getProvince()) && entity.getCity().contains(city)) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                }
            }
        }
        return list;
    }

    private List<RescueForceEntity> getSublist6(SeismicRelationQueryParams queryParams, List defaultModel,
                                                int page, int pageSize) {
        String province = queryParams.getProvince();
        List<RescueForceEntity> list = new ArrayList<>();
        if (page < defaultModel.size()) {
            String city = queryParams.getCity();
            int count = 0;
            for (int i = 0; i < defaultModel.size(); i++) {
                RescueForceEntity entity = (RescueForceEntity) defaultModel.get(i);
                if (PlatformObjectUtils.isEmpty(city)) {
                    if (province.equals(entity.getProvince())) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                } else {
                    if (province.equals(entity.getProvince()) && entity.getCity().contains(city)) {
                        count++;
                        if (count >= page && count <= page + pageSize) {
                            list.add(entity);
                        } else if (count > page + pageSize) {
                            break;
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse selectModel(String taskId, String modelId, String type) {
        SeismicIntensityRelation byTaskId = intensityRelationRepository.getByTaskId(taskId);
        if (PlatformObjectUtils.isNotEmpty(byTaskId)) {
            switch (type) {
                case "1":
                    byTaskId.setModel1Id(modelId);
                    byTaskId.setModel1Type("1");
                    break;
                case "2":
                    byTaskId.setModel2Id(modelId);
                    break;
                case "3":
                    byTaskId.setModel3Id(modelId);
                    break;
                case "4":
                    byTaskId.setModel4Id(modelId);
                    byTaskId.setModel4Type("2");
                    break;
                case "5":
                    byTaskId.setModel5Id(modelId);
                    break;
                case "6":
                    byTaskId.setModel6Id(modelId);
                    break;
            }
            intensityRelationRepository.updateSeismicIntensityRelation(byTaskId);
        } else {
            SeismicIntensityRelation entity = new SeismicIntensityRelation();
            entity.setTaskId(taskId);
            switch (type) {
                case "1":
                    entity.setModel1Id(modelId);
                    entity.setModel1Type("1");
                    break;
                case "2":
                    entity.setModel2Id(modelId);
                    break;
                case "3":
                    entity.setModel3Id(modelId);
                    break;
                case "4":
                    entity.setModel4Id(modelId);
                    entity.setModel4Type("2");
                    break;
                case "5":
                    entity.setModel5Id(modelId);
                    break;
                case "6":
                    entity.setModel6Id(modelId);
                    break;
            }
            saveSeismicIntensityRelation(entity);
        }
        Object obj = null;
        switch (type) {
            case "1":
                obj = intensityAttenuationService.getModelById(modelId);
                break;
            case "2":
                obj = casualtyService.getModelById(modelId);
                break;
            case "3":
                obj = economicLossesService.getModelById(modelId);
                break;
            case "4":
                obj = resettlementPersonnelService.getModelById(modelId);
                break;
            case "5":
                obj = rescueForceService.getModelById(modelId);
                break;
            case "6":
                obj = materialService.getModelById(modelId);
                break;

        }
        return RestResponse.succeed(obj);
    }

    @Override
    public SeismicIntensityRelation getByTaskId(String taskId) {
        return intensityRelationRepository.getByTaskId(taskId);
    }

    @Override
    public RestResponse saveSeismicIntensityRelation(SeismicIntensityRelation entity) {
        entity.setIsDelete(YNEnum.N.toString());
        entity.setId(UUIDGenerator.getUUID());
        int i = intensityRelationRepository.saveSeismicIntensityRelation(entity);
        return ResponseCreator.createSuccessResponse(i, "保存成功！");
    }

    @Override
    public int updateSeismicIntensityRelation(SeismicIntensityRelation entity) {
        return intensityRelationRepository.updateSeismicIntensityRelation(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse saveIntensityAttenuation(String taskId, IntensityAttenuation entity) {
        try {
            IntensityAttenuation save = intensityAttenuationService.save(entity);
            SeismicIntensityRelation byTaskId = intensityRelationRepository.getByTaskId(taskId);
            if (PlatformObjectUtils.isNotEmpty(byTaskId)) {
                byTaskId.setModel1Id(save.getId());
                byTaskId.setModel1Type("1");
                intensityRelationRepository.updateSeismicIntensityRelation(byTaskId);
            } else {
                SeismicIntensityRelation entity1 = new SeismicIntensityRelation();
                entity1.setTaskId(taskId);
                entity1.setModel1Id(save.getId());
                entity1.setModel1Type("1");
                saveSeismicIntensityRelation(entity1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseCreator.createSuccessResponse(entity, "保存成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse saveSettingSeismicProcess(String taskId, SettingSeismicProcess entity,String range) {
        List<SettingSeismicInfluenceflied> settingSeismicInfluenceflieds = settingSeismicInfluencefliedRepository.findByTaskId(taskId);
        if (settingSeismicInfluenceflieds.size() > 0) {
            //删除与任务关联的影响场
            deleteSsiByTaskId(taskId);
            deleteSipByTaskId(taskId);
            preAssessResultService.deleteSeiCapdistribution(taskId);//删除抗震能力分布
            casualtyService.deleteDataPbeIntStrAreaByTaskId(taskId);//删除各烈度下建筑物破坏
        }
        entity.setId(UUIDGenerator.getUUID());
        String userId = PlatformSessionContext.getUserID();
        entity.setCreateUserId(userId);
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        entity.setCreateUser(sUser.getUserName());
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setIsDelete(YNEnum.N.toString());
        int i = intensityRelationRepository.saveSettingSeismicProcess(entity);
        if (i > 0) {
            SeismicIntensityRelation entity1 = intensityRelationRepository.getByTaskId(taskId);
            if (PlatformObjectUtils.isNotEmpty(entity1)) {
                entity1.setModel1Id(entity.getId());
                entity1.setModel1Type("2");
                entity1.setButton1_status1("2");
                entity1.setButton2_status1("0");
                entity1.setButton2_status2("0");
                entity1.setButton2_status3("0");
                entity1.setButton3_status1("0");
                entity1.setButton3_status2("0");
                entity1.setButton4_status1("0");
                entity1.setButton4_status2("0");
                entity1.setButton5_status1("0");
                entity1.setButton6_status1("0");
                entity1.setButton7_status1("0");
                entity1.setButton8_status1("0");
                entity1.setButton8_status2("0");
                entity1.setButton8_status3("0");
                entity1.setButton9_status1("0");
                intensityRelationRepository.updateSeismicIntensityRelation(entity1);
            } else {
                entity1 = new SeismicIntensityRelation();
                entity1.setTaskId(taskId);
                entity1.setModel1Id(entity.getId());
                entity1.setModel1Type("2");
                entity1.setButton1_status1("2");
                entity1.setButton2_status1("0");
                entity1.setButton2_status2("0");
                entity1.setButton2_status3("0");
                entity1.setButton3_status1("0");
                entity1.setButton3_status2("0");
                entity1.setButton4_status1("0");
                entity1.setButton4_status2("0");
                entity1.setButton5_status1("0");
                entity1.setButton6_status1("0");
                entity1.setButton7_status1("0");
                entity1.setButton8_status1("0");
                entity1.setButton8_status2("0");
                entity1.setButton8_status3("0");
                entity1.setButton9_status1("0");
                saveSeismicIntensityRelation(entity1);
            }
        }
        boolean isNa = false;
        BigDecimal longX1 = BigDecimal.ZERO;
        BigDecimal shortY1 = BigDecimal.ZERO;
        //烈度,遍历烈度
        int I2 = 10;
        switch (entity.getEpicenterIntensity()) {
            case "Ⅹ":
                I2 = 10;
                break;
            case "Ⅸ":
                I2 = 9;
                break;
            case "Ⅷ":
                I2 = 8;
                break;
            case "Ⅶ":
                I2 = 7;
                break;
            case "Ⅵ":
                I2 = 6;
                break;
        }

        // List<SettingSeismicDetails> list = new ArrayList<>();

        List<SettingSeismicDetails> settingSeismicDetailsByTaskId = settingSeismicService.getSettingSeismicDetailsByTaskId(taskId);
        for (SettingSeismicDetails settingSeismicDetails : settingSeismicDetailsByTaskId) {
            BigDecimal M = settingSeismicDetails.getEarthquakeLevel(); //震级
            SettingSeismicInfluenceflied influenceflied = new SettingSeismicInfluenceflied();
            influenceflied.setEarthquakeLevel(M);
            isNa = true;
            for (int I = I2; I > 5; I--) {
                influenceflied.setDzIntensity(String.valueOf(I));
                influenceflied.setDataSource("2");//2手动录入
                BigDecimal longX = BigDecimal.ZERO;
                BigDecimal shortY = BigDecimal.ZERO;
                switch (I) {
                    case 10:
                        longX = entity.getLongLength5();
                        shortY = entity.getShortLength5();
                        break;
                    case 9:
                        longX = entity.getLongLength4();
                        shortY = entity.getShortLength4();
                        break;
                    case 8:
                        longX = entity.getLongLength3();
                        shortY = entity.getShortLength3();
                        break;
                    case 7:
                        longX = entity.getLongLength2();
                        shortY = entity.getShortLength2();
                        break;
                    case 6:
                        longX = entity.getLongLength1();
                        shortY = entity.getShortLength1();
                        break;
                }
                influenceflied.setLongX(longX);
                influenceflied.setShortY(shortY);
                influenceflied.setUuid(UUIDGenerator.getUUID());
                influenceflied.setSourceEarthquakeId(settingSeismicDetails.getId());
                String influenceEllipse = null;
                if (!isNa) {
                    //环
                    influenceEllipse = setEarthquakeMapService.createInfluenceEllipse(settingSeismicDetails.getLongitude().toString(),
                            settingSeismicDetails.getLatitude().toString(), influenceflied.getLongX().toString(),
                            influenceflied.getShortY().toString(),
                            String.valueOf(settingSeismicDetails.getAngle()), longX1.toString(), shortY1.toString());
                } else {
                    //椭圆
                    influenceEllipse = setEarthquakeMapService.createInfluenceEllipse(settingSeismicDetails.getLongitude().toString(),
                            settingSeismicDetails.getLatitude().toString(), influenceflied.getLongX().toString(),
                            influenceflied.getShortY().toString(),
                            String.valueOf(settingSeismicDetails.getAngle()), null, null);
                }
                isNa = false;
                longX1 = influenceflied.getLongX();
                shortY1 = influenceflied.getShortY();
                influenceflied.setGeom(influenceEllipse);
                influenceflied.setTaskId(taskId);
                influenceflied.setAssessmentUserId(userId);
                influenceflied.setAssessmentUserDept(sUser.getOrgId());
                influenceflied.setAssessmentTime(PlatformDateUtils.getCurrentTimestamp());
                settingSeismicInfluencefliedRepository.saveSettingSeismicInfluenceflied(influenceflied);
                if (I == 6) {
                    SeismicInfluenceflyPbe seismicInfluenceflyPbe = new SeismicInfluenceflyPbe();
                    seismicInfluenceflyPbe.setUuid(UUIDGenerator.getUUID());
                    seismicInfluenceflyPbe.setDetailsId(settingSeismicDetails.getId());
                    seismicInfluenceflyPbe.setInfluenceflyId(influenceflied.getUuid());

                    influenceEllipse = setEarthquakeMapService.createInfluenceEllipse(settingSeismicDetails.getLongitude().toString(),
                            settingSeismicDetails.getLatitude().toString(), influenceflied.getLongX().toString(),
                            influenceflied.getShortY().toString(),
                            String.valueOf(settingSeismicDetails.getAngle()), null, null);


                    seismicInfluenceflyPbe.setGeom(influenceEllipse);
                    seismicInfluenceflyPbe.setTaskId(taskId);
                    settingSeismicInfluencefliedRepository.saveSeismicInfluenceflyPbe(seismicInfluenceflyPbe);

                    //存储每个点最外圈的地震影响场的点详情的数据
                    // list.add(settingSeismicDetails);
                }
            }
        }
        resultTotalService.saveYpgResult(taskId,range);
        return ResponseCreator.createSuccessResponse(entity, "保存成功！");
    }

    @Override
    public int deleteSsiByTaskId(String taskId) {
        int i = intensityRelationRepository.deleteSsiByTaskId(taskId);
        //逻辑删除导入影响场文件及物理删除相关数据
        influencefliedMapService.deleteFileDataByTaskId(taskId);
        return i;
    }

    @Override
    public int deleteSipByTaskId(String taskId) {
        int i = intensityRelationRepository.deleteSipByTaskId(taskId);
        return i;
    }

    @Override
    public RestResponse getSettingSeismicProcessById(String id) {
        return RestResponse.succeed(intensityRelationRepository.getProcessById(id));
    }

    @Override
    public void updateSeismicIntensityRelationByTaskId(String id) {
        intensityRelationRepository.updateSeismicIntensityRelationByTaskId(id);
    }
}
